import cv2

# 使用 cv2.legacy 模块创建 KCF 追踪器
tracker = cv2.legacy.TrackerKCF_create()

# 打开摄像头
cam = cv2.VideoCapture(0)
if not cam.isOpened():
    print("Error: Camera could not be opened.")
    exit()

# 捕获第一帧，用于选择 ROI
ret, frame = cam.read()
if not ret:
    print("Error: Could not read frame.")
    cam.release()
    exit()

# 选择 ROI
obj = cv2.selectROI("Tracking", frame, fromCenter=False, showCrosshair=True)
cv2.destroyWindow("Tracking")

# 初始化追踪器
ok = tracker.init(frame, obj)

while True:
    # 读取摄像头帧
    ret, frame = cam.read()
    if not ret:
        print("Failed to capture frame.")
        break

    # 更新追踪器
    upd, obj = tracker.update(frame)
    if upd:
        # 绘制跟踪目标的矩形框
        x1 = (int(obj[0]), int(obj[1]))
        x2 = (int(obj[0] + obj[2]), int(obj[1] + obj[3]))
        cv2.rectangle(frame, x1, x2, (255, 0, 0), 2)
    else:
        # 追踪失败时显示提示
        cv2.putText(frame, "Tracking failure", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

    # 显示结果
    cv2.imshow("Track object", frame)

    # 按下 'Esc' 键退出
    if cv2.waitKey(1) & 0xFF == 27:
        break

# 释放资源
cam.release()
cv2.destroyAllWindows()
